import { defineEventHandler, getHeader } from 'h3'
import { adminRoutes } from '../admin-routes-store'
import redis from '../util/redis'

export default defineEventHandler(async (event) => {
  const key = getHeader(event, 'x-admin-key') || ''
  if (!key) {
    return { status: 401, message: 'Unauthorized: missing x-admin-key' }
  }

  try {
    const txt = await redis.get('admin:routes')
    if (txt) {
      try {
        const data = JSON.parse(txt)

        // 如果 redis 中的 routes 数量与内存中的不一致，重载 redis 并返回内存数据
        if (Array.isArray(data.routes) && data.routes.length === adminRoutes.routes.length) {
          return data
        } else {
          try {
            await redis.set('admin:routes', JSON.stringify(adminRoutes))
          } catch (e) {
            // 忽略 redis 写入错误，仍然返回内存数据
          }
          return adminRoutes
        }
      } catch (e) {
        // corrupted JSON in redis, fall back to in-memory and try to re-seed redis
        try {
          await redis.set('admin:routes', JSON.stringify(adminRoutes))
        } catch (e2) {
          // 忽略 redis 写入错误
        }
        return adminRoutes
      }
    }

    // no value in redis -> seed it with the in-memory default (best-effort)
    try {
      await redis.set('admin:routes', JSON.stringify(adminRoutes))
    } catch (e) {
      // ignore redis write errors
    }

    return adminRoutes
  } catch (e) {
    // redis not configured or failed -> fallback to in-memory store
    return adminRoutes
  }
})
